import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import { useTimeZoneStore } from '@/stores/TimeZone';

dayjs.extend(utc);
dayjs.extend(timezone);

/**
 * @description 把时间戳转换成日期格式 YYYY/MM/DD HH:mm:ss
 * @param timestamp 时间戳
 * @returns {string} 格式化后的字符串
 */
export function formatTimestampToDateString(timestamp: number | string): string {
  try {
    return dayjs(timestamp).format('YYYY/MM/DD HH:mm:ss');
  } catch {
    return String(timestamp);
  }
}

export function formatTimestampToDateString2(timestamp: Date | number | string): string {
  try {
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
  } catch {
    return String(timestamp);
  }
}

/**
 * @description 把UTC时间转换成用户当地日期 YYYY/MM/DD HH:mm:ss
 * @param string ISO8601格式字符串
 * @param string 时区
 * @returns {string} 格式化后的字符串
 */
const timeZoneStore = useTimeZoneStore();
export function formatTimestampToLocalDateString(utcTime: string, tz?: string): string {
  try {
    if (!tz) {
      tz = timeZoneStore.timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone;
    }
    return dayjs.utc(utcTime).tz(tz).format(timeZoneStore.timeFormat || 'YYYY-MM-DD HH:mm:ss');
  } catch {
    return String(utcTime);
  }
}
